package helper

import (
	"fmt"
	"github.com/gogf/gf/v2/os/gfile"
	"github.com/gogf/gf/v2/text/gstr"
	"os"
	"strings"
)

var File = fileHelper{}

type fileHelper struct {
	appRootDir string
}

func (r *fileHelper) FormatFilePath(path string, trimBackslash ...bool) string {
	path = gstr.Trim(path)
	if path == "" {
		return ""
	}

	path = gstr.Replace(path, "\\", "/")
	if trimBackslash != nil && len(trimBackslash) > 0 && trimBackslash[0] {
		path = strings.TrimSpace(strings.Trim(path, "/"))
	}

	return path
}
func (r *fileHelper) GetAppRootDir() string {
	if r.appRootDir != "" {
		return r.appRootDir
	}
	r.appRootDir = gfile.SelfDir()
	if gfile.Name(r.appRootDir) == "bin" {
		r.appRootDir = gfile.Dir(r.appRootDir)
	}

	r.appRootDir = r.FormatFilePath(r.appRootDir)
	return r.appRootDir
}
func (r *fileHelper) GetStorageDir(subDir ...string) string {
	storageDir := r.GetAppRootDir() + "/storage"
	s := r.FormatFilePath(gstr.Join(subDir, "/"), true)
	if s != "" {
		storageDir = storageDir + "/" + s
	}
	if !gfile.Exists(storageDir) || !gfile.IsDir(storageDir) {
		err := os.MkdirAll(storageDir, 0755)
		if err != nil {
			return ""
		}
	}

	return storageDir
}

func (r *fileHelper) GetResourceDir(subDir ...string) string {
	s := r.FormatFilePath(gstr.Join(subDir, "/"), true)
	if s != "" {
		s = "/" + s
	}
	return fmt.Sprintf("%s/resource%s", r.GetAppRootDir(), s)
}
func (r *fileHelper) GetI18nDir(subDir ...string) string {
	s := r.FormatFilePath(gstr.Join(subDir, "/"), true)
	if s != "" {
		s = "/" + s
	}
	return fmt.Sprintf("%s/resource/i18n%s", r.GetAppRootDir(), s)
}
func (r *fileHelper) GetTemplateDir(subDir ...string) string {
	s := r.FormatFilePath(gstr.Join(subDir, "/"), true)
	if s != "" {
		s = "/" + s
	}
	return fmt.Sprintf("%s/resource/template%s", r.GetAppRootDir(), s)
}
